package ar.unc.famaf.pln.giveselector.pickers;

import java.util.*;

import ar.unc.famaf.pln.giveselector.context.Context;
import ar.unc.famaf.pln.giveselector.context.Utterance;

/**
 * @author Luciana Benotti
 * @author Alexandre Denis
 */
public class MemoryPicker implements IPicker
{
	private int curIndex;
	private List<Utterance> sortedUtterances = new ArrayList<Utterance>();
	private int planLength;


	@Override
	public Utterance pick(Set<Utterance> utterances, Context context)
	{
		// if the set of candidate utterances changed as a result of a plan change, sort the new set
		// into a circular list and reset the index of the circular list
		if (!new HashSet<Utterance>(sortedUtterances).equals(utterances))
		{
			curIndex = 0;
			sortedUtterances = sort(utterances);
			planLength = context.getFutureActions().size();
		}

		if (sortedUtterances.isEmpty())
			return null;
		else
		{
			Utterance ret = sortedUtterances.get(curIndex);
			curIndex++;
			if (curIndex>=sortedUtterances.size())
				curIndex = 0;
			System.out.println("===== MEMORY PICKER ");
			System.out.println("Picked: [" + ret.getId() + "] " + ret.getText());
			System.out.println("==========================================");
			return ret;
		}		
	}


	/**
	 * Sorts the given Utterances.
	 */
	protected List<Utterance> sort(Set<Utterance> utterances)
	{
		List<Utterance> ret = new ArrayList<Utterance>(utterances);
		Collections.sort(ret, new Comparator<Utterance>()
		{
			public int compare(Utterance u1, Utterance u2)
			{
				return u2.getResponse().getDiscretizedActions().size() - u1.getResponse().getDiscretizedActions().size();
			}
		});
		return ret;
	}

}
